import regeneratorRuntime from '../../../../resource/libs/runtime'
import { asyncReverseGeocoder, asyncCalculateDistance } from '../../../../common/utils'
import service from '../../../../common/service'

let app = getApp()

Page({
  data: {
    id: '',
    loading: false
  },

  onLoad ({ id }) {
    if (id) {
      this.setData({ id }, () => {
        this.getOrder()
      })
    }
  },

  async onPullDownRefresh () {
    if (this.data.id) {
      await this.getOrder()
    }
    wx.stopPullDownRefresh()
  },

  async getOrder () {
    if (this.data.loading) { return }
    this.setData({ loading: true })
    let id = this.data.id
    let res = await service.getPromise('order/mini', { id })
    this.setData({ loading: false })
    if (res && typeof res !== 'number') {
      let { data } = res
      let address = ''
      let km = 0
      let time = 0
      if (data.state === 2) {
        if (data.begin === 1) {
          let l_res = await asyncReverseGeocoder({
            location: {
              latitude: data.driver_lat,
              longitude: data.driver_lng
            }
          })
          if (l_res) {
            address = l_res.result.address
          }
        } else {
          let d_res = await asyncCalculateDistance({
            mode: 'driving',
            from: {
              latitude: data.driver_lat,
              longitude: data.driver_lng
            },
            to: [app.global_data.o_location]
          })
          if (d_res) {
            let { result } = d_res
            let { elements } = result
            km = (elements[0].distance / 1000).toFixed(1)
            time = (elements[0].duration / 60).toFixed(0)
          }
        }
      }
      this.setData({ ...data, address, km, time })
    }
  },

  phoneTap () {
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },

  payTap () {
    wx.navigateBack({
      delta: 1
    })
  }
})